package com.dezheyun.config;

import com.dezheyun.service.DzUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private DzUserService dzUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 将认证管理注入到IOC容器中
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(dzUserService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //设置那些页面可以直接访问，那些需要验证
                .antMatchers("/login.html", "/error").permitAll() //放过
                //.antMatchers("/query").hasRole("root")
                .anyRequest().authenticated() //剩下的所有地址都是需要在认证状态下才可以访问的
                .and()
                .formLogin()
                .loginPage("/login.html")  //指定要跳转的登录界面
                .loginProcessingUrl("/login") //处理认证路径请求
                .defaultSuccessUrl("/home") //登录成功跳转的默认页面
                .failureForwardUrl("/error") //错误页面
                .and()
                .logout()  //登出
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")//退出成功跳转的默认页面
                .and().rememberMe()
                .and().csrf().disable();  //防止跨域伪造
    }

    @Bean
    public PersistentTokenRepository tokenRepository(DataSource dataSource) {
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource);
        //第一次创建表结构，第二次的时候注释掉就可以
        //repository.setCreateTableOnStartup(true);
        return repository;
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
